<template>
  <div class="game-box" ref="gameBox">
    <div class="game-header">
      闯关步数：{{ curIndex }}
      <CountDownCom ref="CountDownComRef" :duration="durationRef" @onFinish="onFinish" />
      <el-button class="resetBtn" :plain="true" @click="resetGame">重置</el-button>
    </div>
    <div class="game-body" ref="gameBodyRef"></div>
    <ul id="ditu" ref="ulRef">
      <li
        v-for="(todo, index) in list"
        :key="index"
        :class="{ isEmpty: todo.isEmpty, activeLi: todo.index === curIndex }"
      >
        <span class="houzi">{{ todo.index === curIndex ? "🐒" : "" }}</span>
        <span class="addSecond">{{ todo.addSecond > 0 &&  todo.index > curIndex? todo.addSecond : "" }}</span>
      </li>
    </ul>
  </div>
</template>
  
  <script setup>
import { ref, onMounted, onBeforeUnmount,nextTick } from "vue";
import { ElMessage } from "element-plus";
import CountDownCom from "./CountDownCom.vue";


let len = 100; // 地图长度
let timeTotal = 15 // 倒计时
let gameMapList = initGameMap(len);
const ulRef = ref(null);
const gameBox = ref(null);
const gameBodyRef = ref(null);
const curIndex = ref(0); // 当前位置
const durationRef = ref(timeTotal); // 倒计时
const list = ref(gameMapList);
const timeEnd = ref(false);
const CountDownComRef = ref(null);
function resetGame() {
  curIndex.value = 0;
  timeEnd.value = false;
  durationRef.value = timeTotal;
  list.value = initGameMap(len);
  ulRef.value.scrollTo({
    left: 0,
    behavior: "smooth", // 平滑滚动
  });
  nextTick(() => {
    CountDownComRef.value.startTimer()
    CountDownComRef.value.remainingTime = timeTotal;
    CountDownComRef.value.countdown()
  })
}
// 处理左右箭头键事件
const handleKeyUp = (event) => {
  if (list.value[curIndex.value].isEmpty) {
    ElMessage({
      message: "不能跳到空白格,失败了，重新来过",
      type: "error",
    });
    return;
  }  
  if (timeEnd.value) {
    ElMessage({
      message: "时间到，重新来过",
      type: "error",
    });
    return;
  }  
  if (event.key === "j" || event.key === "J") {
    curIndex.value += 1;
    // 执行按下 J 键时的相关操作
  } else if (event.key === "k" || event.key === "K") {
    curIndex.value += 2;
    // 执行按下 K 键时的相关操作
  } else if (event.key === "l" || event.key === "L") {
    curIndex.value += 3;
    // 执行按下 K 键时的相关操作
  }
  if (list.value[curIndex.value].isEmpty) {
    ElMessage({
      message: "不能跳到空白格,失败了，重新来过",
      type: "error",
    });
    CountDownComRef.value.stopTimer()
    return;
  }
  if (curIndex.value >= len) {
    curIndex.value = len - 1;
    ElMessage({
      message: "到头了，重新来过",
      type: "success",
    });
    return;
  }
  CountDownComRef.value.remainingTime += list.value[curIndex.value].addSecond 
  const element = document.querySelector("#ditu .activeLi");
  scrollToLiElement(ulRef.value, element);
  // if (event.key === "ArrowLeft") {
  //     curIndex.value +=1
  // }
  // if (event.key === "ArrowRight") {
  //     curIndex.value +=2

  // }
  // CountDownComRef.value.countdown()
};
const handleResize = () => {
  const { diagonalLength, angleDegrees } = getDiagonalInfo(gameBodyRef.value);
  ulRef.value.style.width = `${diagonalLength}px`;
  ulRef.value.style.transform = `rotate(-${angleDegrees}deg)`;
};
//   绑定事件
onMounted(() => {
  document.addEventListener("keyup", handleKeyUp);
  window.addEventListener("resize", handleResize);
  handleResize();
  console.debug('%c  CountDownComRef','font-size:30px;',CountDownComRef)
});
onBeforeUnmount(() => {});

function onFinish() {
  timeEnd.value = true;
  ElMessage({
    message: "时间到，重新来过",
    type: "error",
  })
}
function scrollToLiElement(ulElement, liElement) {
  if (ulElement && liElement) {
    // 计算目标 li 元素相对于 ul 元素的位置
    const ulRect = ulElement.getBoundingClientRect();
    const liRect = liElement.getBoundingClientRect();
    const scrollLeft = liRect.left - ulRect.left + ulElement.scrollLeft;

    ulElement.scrollTo({
      left: scrollLeft,
      behavior: "smooth", // 平滑滚动
    });
  }
}
function getDiagonalInfo(element) {
  // 获取元素的宽度和高度
  const width = element.offsetWidth;
  const height = element.offsetHeight;

  // 计算对角线长度
  const diagonalLength = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2));

  // 计算对角线与水平轴之间的角度（弧度）
  const angleRadians = Math.atan(height / width);

  // 将弧度转换为度
  const angleDegrees = angleRadians * (180 / Math.PI);

  return {
    diagonalLength,
    angleDegrees,
  };
}
// 初始化路线
function initGameMap(len) {
  let gameMapList = []; // 游戏列表
  //  初始化路线
  for (let i = 0; i < len; i++) {
    let isEmpty = Math.random() > 0.5;
    if (i >= 2) {
      if (isEmpty) {
        if (gameMapList[i - 1].isEmpty && gameMapList[i - 2].isEmpty) {
          isEmpty = false;
        }
      } else {
        if (
          i >= 4 &&
          !gameMapList[i - 1].isEmpty &&
          !gameMapList[i - 2].isEmpty &&
          !gameMapList[i - 3].isEmpty
        ) {
          isEmpty = true;
        }
      }
    } else {
      isEmpty = false;
    }
    gameMapList.push({
      isEmpty,
      index: i,
      addSecond: isEmpty ? 0 : Math.floor(Math.random() * 3),
    });
  }
  return gameMapList;
}

</script>
  
  <style>
.game-box {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
  padding: 40px;
}
.game-box .game-header {
  flex-basis: 50px;
}
.game-body {
  flex: 1;
}
#ditu {
  display: flex;
  transform: rotate(-45deg);
  transform-origin: left;
  overflow: auto;
  position: absolute;
  left: 10px;
  bottom: 70px;
  left: 0;
  bottom: 0;
  width: 550px;
}

#ditu li {
  flex-basis: 50px;
  height: 60px;
  border-bottom: 3px solid #000;
  flex-shrink: 0;
  list-style: none;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 4px;
}
#ditu li .houzi {
  position: absolute;
  font-size: 50px;
  transform: rotateX("angle");
}
#ditu li.isEmpty {
  border-bottom: none;
}
#ditu::-webkit-scrollbar {
  display: none;
}
.resetBtn {
  margin-left: 10px;
}
</style>
  